<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\PostModel;
use app\model\UserModel;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
//use GatewayClient\Gateway;
use think\facade\Db;
use think\Request;

class User extends Base
{

//    获取用户个人基本信息
    public static function getUser_Basic(Request $request)
    {
        $token = $request->param('token');
        $user_now = $request->param('user_now');  //判断查询的是当前登录用户还是其他用户

        if(isset($user_now)){
            $user_id = $request->param('user_id');
        }
        else{

            $user_id = UserModel::getUseridByToken($token);
        }


        $user = UserModel::where('user_id', $user_id)->find();
        $json['user_id'] = $user['user_id'];
        $json['username'] = $user['user_name'];
        $json['birthday'] = $user['birthday'];
        $json['sex'] = $user['sex'];
        $json['email'] = $user['email'];
        $json['hobby'] = $user['hobby'];
        $json['profile'] = $user['profile'];
        $json['city'] = $user['city'];
        $json['credit'] = $user['credit'];
        $json['identity'] = $user['identity'];
        $json['img'] = $user['img'];
        $json['ifcheck'] = $user['ifcheck'];


        //        该用户关注的人数
        $cnt_attention = $user->table('attention')
            ->where('subscribe', $user_id)
            ->count('be_subscribe');

//        该用户的粉丝人数
        $cnt_fans = $user->table('attention')
            ->where('be_subscribe', $user_id)
            ->count('subscribe');

        $json['cnt_attention'] =$cnt_attention;
        $json['cnt_fans'] =$cnt_fans;


//        内容评论数
        $post=new PostModel();
        $cnt_post_comment=$post->table('post_comment a,post b')
            ->where('b.user_id',$user_id)
            ->where('b.post_id = a.post_id')
            ->count('a.post_comment_id');

        $json['cnt_post_comment'] =$cnt_post_comment;

        return json($json);
    }

//    获取当前登录用户的身份验证信息
    public static function getUser_Identity(Request $request)
    {

        $token = $request->param('token');
        $user_id = UserModel::getUseridByToken($token);

        if (null == $token) {
            return json(array(['msg' => '无token']));
        }

        $user = UserModel::where('user_id', $user_id)->find();
        $json['ifcheck'] = $user['ifcheck'];
        $json['identity'] = $user['identity'];
        $json['sno'] = $user['sno'];
        $json['true_name'] = $user['true_name'];
        $json['faculty'] = $user['faculty'];
        $json['grade'] = $user['grade'];
        $json['subject'] = $user['subject'];


        return json($json);
    }

//    获取当前登录用户的账号信息
    public static function getUser_Account(Request $request)
    {

        $token = $request->param('token');
        $user_id = UserModel::getUseridByToken($token);

        if (null == $token) {
            return json(array(['msg' => '无token']));
        }

        $user = UserModel::where('user_id', $user_id)->find();
        $json['phone'] = $user['phone'];

        return json($json);
    }

    //获取当前登录用户 所关注的用户
    public static function getMyAttention(Request $request)
    {
        $user_id = UserModel::getUseridByToken($request->param(('token'))); //获取用户id

        $db = new UserModel();

        $info = $db->table('attention a,user b')
            ->where('a.subscribe', $user_id)
            ->where('a.be_subscribe = b.user_id')
            ->select();

        $total = $db->table('attention a,user b')
            ->where('a.subscribe', $user_id)
            ->where('a.be_subscribe = b.user_id')
            ->count('a.be_subscribe');

        return json(['code' => 1, 'data' => $info, 'total' => $total]);


    }

//   取消关注
    public function cancelAttention(Request $request)
    {
        $attention_id = $request->param('attention_id');

        if($attention_id==null){
            $be_user_id=$request->param('user_id'); //获取用户id
            $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id
            $res = Db::table('attention')
                ->where('subscribe',$user_id)
                ->where('be_subscribe', $be_user_id)
                ->delete();
            if ($res) {
                return json(['code' => 1]);
            } else {
                return json(['code' => 0]);
            }

        }
        else{
            $res = Db::table('attention')
                ->where('attention_id', $attention_id)
                ->delete();

            if ($res) {
                return json(['code' => 1]);
            } else {
                return json(['code' => 0]);
            }
        }

    }

    //查看关注情况
    public function Attention_Info(Request $request){
        $be_user_id=$request->param(('user_id')); //获取用户id
        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id
        $res = Db::table('attention')
            ->where('subscribe',$user_id)
            ->where('be_subscribe', $be_user_id)
            ->find();
        if ($res!=null) {
//            已关注
            return json(['code' => 1]);
        } else {
//            未关注
            return json(['code' => 0]);
        }

    }

//    关注用户
    public function Attention(Request $request){

        $be_user_id=$request->param(('user_id')); //获取用户id
        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id

        $data=['subscribe'=>$user_id,'be_subscribe'=>$be_user_id];

        $res = Db::table('attention')
            ->insert($data);

        if ($res) {
            return json(['code' => 1]);
        } else {
            return json(['code' => 0]);
        }


    }

//    修改个人基本信息
    public function updateUser_Basic(Request $request)
    {

        $user_name = $request->param('user_name');
        $user_id = $request->param('user_id');
//        $user_token = $request->param('user_token');

        if (!isset($user_id)) {  //用户端修改个人基本信息
            $user_id = UserModel::getUseridByToken($request->param(('token'))); //获取用户id
        }

//验证新的用户名是否已经存在


//   输入的用户名与原先的不相同
        if ($user_name != UserModel::getNameByUserid($user_id)) {

            $other_user = Db::table('user')->where('user_id', '<>', $user_id)
                ->where('user_name', $user_name)->find();

            if ($other_user != null) {
                return json(['code' => -1]); // 该用户名已存在
            }
        }

        $PersonBasic = $request->param('PersonBasic');

        $user = UserModel::find($user_id);

        if ($user->save($PersonBasic)) {
            return json(['code' => 1]);
        }

        return json(['code' => 0]);

    }

//修改账号信息（用户端）
    public function updateUserAccountByUser(Request $request)
    {

        $token = $request->param('token');

        //        验证旧密码是否正确
        $user_id = UserModel::getUseridByToken($request->param(('token'))); //获取用户id
        $old_pwd = $request->param('old_pwd');
        $user = UserModel::find($user_id);

        if ($user['password'] != md5($old_pwd)) {
            return json(['result' => 2, 'msg' => '旧密码错误']);
        }


        $phone = $request->param('phone');

//新手机号
        if ($phone != UserModel::getPhoneByUserid($user_id)) {

//验证新手机号是否已经注册
            $other_user = Db::table('user')->where('user_id', '<>', $user_id)
                ->where('phone', $phone)->find();

            if ($other_user != null) {

                return json(['result' => -1]); // 该手机号已经注册过
            }
        }
//        手机号与原先相同

        $token = md5($request->param('new_pwd'));
        $data = ['password' => $token, 'token' => $token, 'phone' => $phone];

//        更新信息
        if ($user->save($data)) {

            return json(['result' => 1, 'token' => $token]);  //更新成功

        } else {
            return json(['result' => 0]);  //更新失败
        }

    }

//提交（修改）身份验证信息（用户端）
    public function updateUserIdentityByUser(Request $request)
    {

        $user_id = UserModel::getUseridByToken($request->param(('token'))); //获取用户id
        $PersonIdentity = $request->param('PersonIdentity');

        $user = new UserModel();

        $data = ['ifcheck' => 0];

        $result = $user->where('user_id', $user_id)->save($PersonIdentity);

        //内容未修改，是否审核ifcheck不变
        if ($result == 0) {

            return json(['result' => 2]);

        } //修改了内容 ,需要重新审核
        else if ($result != 0) {

            $new = UserModel::find($user_id);

            $new_identity = $new->identity;  //更新内容后的身份

            $res_check = $new->save($data);  //修改字段是否审核为 —— 0 审核中

            if ($res_check) {
                return json(['result' => 1, 'identity' => $new_identity, 'ifcheck' => 0]);  //更新成功
            }

        } //修改失败
        else {

            return json(['result' => 0]);  //更新失败
        }

        return json(['result' => 0]);  //更新失败

    }

    //根据用户ID删除用户
    public function deleteUserByUserID(Request $request)
    {

        $user_id = $request->param('user_id');
        $user = UserModel::find($user_id);

        if ($user == null) {
            return json(['code' => 0]);  //用户不存在
        }

        $user_img=$user['img'];

        $user_img_url= FILEDIR.'user_img/'.$user_img;

        if($user->delete()){
            if($user_img != 'default_user_img.jpg'){
               unlink($user_img_url);
            }
            // 删除帖子、闲置物品文件
            $post_dir=FILEDIR.'post_img/'.$user_id.'/';
            $idle_dir=FILEDIR.'idle_img/'.$user_id.'/';

            if(is_dir($idle_dir)) {
                if($dir_handle=@opendir($idle_dir)) {
                    while(false!==($filename=readdir($dir_handle))) {
                        $file=$idle_dir."/".$filename;
                        if($filename!="." && $filename!="..") {
                            if(is_dir($file)) {
                                $this->del_trash($file);
                            } else {
                                unlink($file);
                            }
                        }
                    }
                    closedir($dir_handle);
                }
                rmdir($idle_dir);
            }

            if(is_dir($post_dir)) {
                if($dir_handle=@opendir($post_dir)) {
                    while(false!==($filename=readdir($dir_handle))) {
                        $file=$post_dir."/".$filename;
                        if($filename!="." && $filename!="..") {
                            if(is_dir($file)) {
                                $this->del_trash($file);
                            } else {
                                unlink($file);
                            }
                        }
                    }
                    closedir($dir_handle);
                }
                rmdir($post_dir);
            }

            return json(array(
                'code' => 1
            ));

       }

        return json(array(
            'code' => 0
        ));

    }

//    批量删除用户
    public function deleteMutipleUser(Request $request){

        $user_ids = $request->param('user_id');

        foreach ($user_ids as $ids){

            $user = UserModel::find($ids);

            if ($user == null) {
                return json(['code' => 0]);  //用户不存在
            }

            $user_img=$user['img'];

            $user_img_url= FILEDIR.'user_img/'.$user_img;

            if($user->delete()){
                if($user_img != 'default_user_img.jpg'){
                    unlink($user_img_url);
                }
                // 删除帖子、闲置物品文件
                $post_dir=FILEDIR.'post_img/'.$ids.'/';
                $idle_dir=FILEDIR.'idle_img/'.$ids.'/';

                if(is_dir($idle_dir)) {
                    if($dir_handle=@opendir($idle_dir)) {
                        while(false!==($filename=readdir($dir_handle))) {
                            $file=$idle_dir."/".$filename;
                            if($filename!="." && $filename!="..") {
                                if(is_dir($file)) {
                                    $this->del_trash($file);
                                } else {
                                    unlink($file);
                                }
                            }
                        }
                        closedir($dir_handle);
                    }
                    rmdir($idle_dir);
                }

                if(is_dir($post_dir)) {
                    if($dir_handle=@opendir($post_dir)) {
                        while(false!==($filename=readdir($dir_handle))) {
                            $file=$post_dir."/".$filename;
                            if($filename!="." && $filename!="..") {
                                if(is_dir($file)) {
                                    $this->del_trash($file);
                                } else {
                                    unlink($file);
                                }
                            }
                        }
                        closedir($dir_handle);
                    }
                    rmdir($post_dir);
                }
            }
            else{
                return json(array(
                    'code' => 0
                ));
            }

        }

        return json(array(
            'code' => 1
        ));

    }


    //获取所有用户信息（管理员权限的）
    public function getAllUserInfo()
    {
        return UserModel::getAllUserInfo();
    }

//修改账号信息（管理员端）
    public function updateUserAccountByAdmin(Request $request)
    {

        $phone = $request->param('phone');
        $user_id =$request->param('user_id'); //获取用户id

        $user = UserModel::find($user_id);


//新手机号
        if ($phone != UserModel::getPhoneByUserid($user_id)) {

//验证新手机号是否已经注册
            $other_user = Db::table('user')->where('user_id', '<>', $user_id)
                ->where('phone', $phone)->find();

            if ($other_user != null) {

                return json(['result' => -1]); // 该手机号已经注册过
            }
        }
//        手机号与原先相同

        $token = md5($request->param('new_pwd'));
        $data = ['password' => $token, 'token' => $token, 'phone' => $phone];

//        更新信息
        if ($user->save($data)) {

            return json(['result' => 1, 'token' => $token]);  //更新成功

        } else {
            return json(['result' => 0]);  //更新失败
        }

    }

//    根据user_id审核用户身份信息（管理员端）
    public function updateCheckByUserId(Request $request){

        $user_ids= $request->param('user_id');
        $user_id_check=$request->param('user_id_check');
        $data=['ifcheck' => $user_id_check];

//批量审核
        if(is_array($user_ids)){

            foreach ($user_ids as $ids){

                $user=UserModel::find($ids);
                if($user->save($data)){}
                else{
                    return json(['code'=>0]);
                }

            }

            return json(['code'=>1]);
        }
        else{
            $user=UserModel::find($user_ids);

            if($user->save($data)){
                return json(['code'=>1]);
            }
            return json(['code'=>0]);
        }




    }

//提交（修改）身份验证信息（管理员端）
    public function updateUserIdentityByAdmin(Request $request)
    {

        $user_id = $request->param('user_id'); //获取用户id
        $PersonIdentity = $request->param('PersonIdentity');

        $user = new UserModel();

        $data = ['ifcheck' => 1];

        $result = $user->where('user_id', $user_id)->save($PersonIdentity);

        if ($result != 0) {

            $new = UserModel::find($user_id);
            $res_check = $new->save($data);  //修改字段是否审核为 1 审核通过

            if ($res_check) {
                return json(['result' => 1]);  //更新成功
            }

        }
        return json(['result' => 0]);  //更新失败

    }

//    判断user_id是否是当前登录用户
    public function judgeUser(Request $request){
        $user_id = $request->param('user_id'); //获取用户id
        $login_user_id = UserModel::getUseridByToken($request->param(('token'))); //获取当前登录用户id

        if($user_id==$login_user_id){
            return json(['code' => 1]);
        }
        else{
            return json(['code' => 0]);
        }

    }

//    删除文件
    private function del_trash(string $file)
    {
       unlink($file);
    }

//    查询当前用户，今天是否已打卡签到
    public function checkClock(Request $request){

        $user_id = UserModel::getUseridByToken($request->param(('token'))); //获取当前登录用户id
        $res=Db::name('clock')
            ->where('user_id',$user_id)
            ->order('clock_id','desc')   //降序
            ->limit(1)
            ->find();

        if($res!=null){
//            获取打卡签到日期
            $res_date=$res['clock_time'];

            $db_year = substr($res_date,0,4);
            $db_month = substr($res_date,5,2);
            $db_day = substr($res_date,8,2);
            //获取php当前的日期
            $this_year = date("Y");
            $this_month = date("m");
            $today = date("d");
            $clicked_time = $this_year."-".$this_month."-".$today;
            //判断是否相等
            if($db_year == $this_year && $db_month == $this_month && $db_day == $today){
                return json(['code' => 1,'clicked_time'=> $clicked_time]);
            }else{
                return json(['code' => 0]);
            }

        }
        return json(['code' => 0]);



    }

//    签到
    public function clockByUser(Request $request){

        //获取php当前的日期、时间
        date_default_timezone_set("Asia/Shanghai");
        $date=date_create();
        $clicked_time = date_format($date,"Y-m-d H:i:s");
        $return_day = date_format($date,"Y-m-d");


        $user_id = UserModel::getUseridByToken($request->param('token')); //获取当前登录用户id
        $data=['user_id'=>$user_id,'clock_time'=>$clicked_time];
        $res=Db::name('clock')->insert($data);
        if($res){

            $user=UserModel::find($user_id);
            $user_credit=$user->credit;
            $new_credit=$user_credit+10;
            $new_data=['credit'=>$new_credit];
            if($user->save($new_data)){
                return json(['code' => 1,'return_day'=>$return_day]);
            }else{
                return json(['code' => 0]);
            }

        }else{
            return json(['code' => 0]);
        }

    }

//    查询当前登录用户所有已打卡日期
    public function getUserClockData(Request $request){
        $user_id = UserModel::getUseridByToken($request->param(('token'))); //获取当前登录用户id
        $date=Db::name('clock')
            ->where('user_id',$user_id)
            ->order('clock_id','desc')   //降序
            ->select();


        $cnt=Db::name('clock')
            ->where('user_id',$user_id)
            ->order('clock_id','desc')   //降序
            ->count('clock_id');

        return json(['code' => 1,'date'=>$date,'clock_days'=>$cnt]);
    }

//    获取积分排行榜
    public function getUserCreditList(){

        $user=new UserModel();
        $user_all=$user->where('ifcheck',1)
                       ->order('credit','desc')
                       ->limit(10)
                       ->select();

        return json(['code' => 1,'userlist'=>$user_all]);

    }

//    计算用户数量
    public function getUserCnt(){

        $user=new UserModel();
//        通过审核
        $stu_ok=$user->where('identity',0)
                     ->where('ifcheck',1)
                     ->count('user_id');
        $tea_ok=$user->where('identity',2)
                     ->where('ifcheck',1)
                     ->count('user_id');
        $senior_ok=$user->where('identity',1)
                        ->where('ifcheck',1)
                        ->count('user_id');
//        审核不通过
        $stu_nook=$user->where('identity',0)
            ->where('ifcheck',2)
            ->count('user_id');
        $tea_nook=$user->where('identity',2)
            ->where('ifcheck',2)
            ->count('user_id');
        $senior_nook=$user->where('identity',1)
            ->where('ifcheck',2)
            ->count('user_id');

//        待审核
        $stu=$user->where('identity',0)
            ->where('ifcheck',0)
            ->count('user_id');
        $tea=$user->where('identity',2)
            ->where('ifcheck',0)
            ->count('user_id');
        $senior=$user->where('identity',1)
            ->where('ifcheck',0)
            ->count('user_id');

        return json(['code' => 1,'stu_cnt_ok'=>$stu_ok,'tea_cnt_ok'=>$tea_ok,'senior_cnt_ok'=>$senior_ok,
        'stu_nook'=>$stu_nook,'tea_nook'=>$tea_nook,'senior_nook'=>$senior_nook,
           'stu'=>$stu,'tea'=>$tea,'senior'=>$senior ]);

    }

//    获取当前登录用户id、用户名、头像图片
    public function getNowUserIdByToken(Request $request){

        $user_id = UserModel::getUseridByToken($request->param(('token'))); //获取当前登录用户id
        $user=UserModel::find($user_id);
        $user_name=$user['user_name'];
        $user_img=$user['img'];

        return json(['code' => 1,'user_id'=>$user_id,'user_name'=>$user_name,'user_img'=>$user_img]);
    }

//    public function getBind(Request $request)
//    {
//        $token = $request->param('token');
//        $client_id = $request->param('client_id');
//        if($token) // 有token
//        {
//            // 解析token，判断有无用户名
//            $decode = JWT::decode($token, new Key('you_are_login','HS256'));
////            $user_id =$decode['user_id'];
//            $token = $request->param('token');
//            $user_id = UserModel::getUseridByToken($token);
//            Gateway::bindUid($client_id,$user_id);
//            Gateway::sendToClient($client_id,json_encode(array('msg'=>'连接成功','user_id'=>$user_id)));
//
//            return json(array('type'=>'joined'));
//        }
//        else
//        {
//            Gateway::sendToClient($client_id,'非法连接');
//
//        }
//
//    }



}











